package com.hubao.flutter_weight_parser.protocol.meta;

import com.hubao.flutter_weight_parser.protocol.JavaScriptWeightProtocol;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;


/**
 * 对应js的class 关系
 * <p>
 * 这边只做名称的区别
 */
public class JavaScriptWeightProtocolClass {

    /**
     * 导出模块
     */
    private final NativeObject modules;

    private final String clazzName;

    public static final Object[] EMPTY_ARGS = new Object[]{};


    public JavaScriptWeightProtocolClass(NativeObject modules, String clazzName) {
        this.modules = modules;
        this.clazzName = clazzName;
    }

    /**
     * 根据元数据实例化一个对应的协议对象
     */
    public JavaScriptWeightProtocol instance(Context context, Scriptable scope) {
        Function clazz = (Function) this.modules.get(this.clazzName);
        try {
            Scriptable object = (Scriptable) clazz.call(context, clazz, clazz, EMPTY_ARGS);
            return new JavaScriptWeightProtocol(context, scope, object);
        }finally {
            clazz = null;
        }
    }

    public String getClazzName() {
        return clazzName;
    }
}
